package grapid.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import javax.servlet.http.HttpServletResponse;

/**
 * 请求头缓存设置类
 * 
 * @author 来源于网络
 * @version 1.0
 * 
 */
public class GCacheHeader {

	/**
	 * 设置缓存头
	 * 
	 * @param cacheTime
	 *            缓存时间，以秒为单位；设为0则不缓存页面
	 * @param response
	 * @return 当前缓存时间
	 */
	public static String setCacheHeader(int cacheTime, HttpServletResponse response) {
		Date date = new Date();
		SimpleDateFormat dateFormatter = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z", Locale.US);
		dateFormatter.setTimeZone(TimeZone.getTimeZone("GMT"));
		String gmtTime = dateFormatter.format(date);
		if (cacheTime > 0) {
			response.setHeader("Cache-Control", "max-age=" + cacheTime);
			response.setDateHeader("Expires", date.getTime() + cacheTime * 1000);
			response.addHeader("Last-Modified", gmtTime);
		} else {
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
		}
		return gmtTime;
	}

}
